// app.js
// Page = require('./utils/wxWOW')
const request = require('./utils/request.js');
const config = require('./utils/config.js');
App({
  onLaunch: function (options) {
    // 获取设备信息
    this.getSystemInfo()
    this.init();
    this.checkUpdateVersion(); //更新版本号
  },
  async init() {
    //  await this.getPrivatekey(); // 请求公钥
    //  await this.init_config(); // 等待请求数据成功后
    var that =this;
    // if (!wx.getStorageSync('token')||!wx.getStorageSync('userInfo')) {
    //     that.login()
    // }


  },
  globalData: {
    isIPhone6: false, //当前设备是否为 iPhone 6
    userInfo: null,
    openid:null,
    is_show:0,
    mapSdkKey: '456BZ-M7VWL-CUNPQ-MHRZW-P2LUE-5SBLJ',
    mapSdkSk: 'XuUCHWTFLnjO0riCyxd0wafhXMIIPPeh',
    lat:'',
    lng:'',
    is_need_refresh:false,
     //默认城市
     defaultCity:'',
  },
  // 初始化获取用户信息
  init_userInfo: function (is_need_refresh=false) {
    return new Promise((resolve, reject) => {

      if (this.globalData.userInfo&&!is_need_refresh) {
        resolve(this.globalData.userInfo);
      } else {

        if(!wx.getStorageSync('token')){

          resolve(null)
        }else{
          request.requestLoading(
              "/api/login/index",
              {},
              'GET',
          ).then((res) => {
              console.log('11111111111')
             console.log(res);
            if(res.code!=1){
              wx.setStorageSync('token','')
              wx.setStorageSync('userInfo','')
              resolve(res.data);
            }
            console.log(res)
            this.globalData.userInfo = res.data;
            resolve(res.data);
          }).catch((err) => {
            // console.error(err);
            reject(err);
          });
        }
      }
    })
  },
  login(is_login = 0) {
    return new Promise((resolve, reject) => {
      var that =this;
      if(that.globalData.is_show==1){
        setTimeout( resolve(that.globalData.userInfo),1500)
      }
      that.globalData.is_show =1;
      //调用登录接口
      wx.login({
        success: function (res) {
          if (that.globalData.userInfo&&!is_login) {
            resolve(that.globalData.userInfo)
          }
          if (res.code) {
            if (is_login == 0) {
              wx.showLoading({
                title: '登录中...',
              })
            }
            request.requestLoading(
                "/api/login/userLogin",
                {
                  code: res.code,

                },
                'POST',
                true,
            ).then((res) => {
              console.log(res)
              wx.hideLoading();
              if (is_login == 0) {
                wx.hideLoading();
              }


              if (res.code == 1) {
                if (res.data.need_login_type == 2) {
                  wx.setStorageSync('token', '');
                  wx.setStorageSync('openid', res.data.openid);
                  if(res.data.authorization_status==2){
                    wx.setStorageSync('authorization_status', res.data.authorization_status)
                  }
                  resolve(null);
                } else {
                  wx.setStorageSync('openid', res.data.openid);
                  wx.setStorageSync('token', res.data.userinfo.token);
                  wx.setStorageSync('mobile', res.data.userinfo.mobile);
                  wx.setStorageSync('userInfo', res.data.userinfo)

                  that.globalData.userInfo = res.data.userinfo;
                  resolve(res.data.userinfo);
                }
              } else {
                if (is_login == 0) {
                  wx.showToast({
                    title: res.msg,
                    icon: 'text',
                    duration:2000
                  });
                  resolve(null)
                } else {
                  cb && cb(res);
                  reject(err);
                }
              }
            }).catch((err) => {
              // wx.showModal({
              //   title: '温馨提示',
              //   content: err.errMsg,
              //   showCancel: false
              // });
              wx.hideLoading()
              reject(err);
            });
          } else {
            console.log("用户失败")
          }
        }
      });
    })
  },

  checkUpdateVersion() {
    //判断微信版本是否 兼容小程序更新机制API的使用
    if (wx.canIUse('getUpdateManager')) {
      //创建 UpdateManager 实例
      const updateManager = wx.getUpdateManager();
      //检测版本更新
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          //监听小程序有版本更新事件
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否马上重启小程序？',
              success: function (res) {
                if (res.confirm) {
                  //TODO 新的版本已经下载好，调用 applyUpdate 应用新版本并重启 （ 此处进行了自动更新操作）
                  updateManager.applyUpdate();
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新版本下载失败
            wx.showModal({
              title: '已经有新版本喽~',
              content: '请您删除当前小程序，到微信 “发现-小程序” 页，重新搜索打开哦~',
            })
          })
        }
      })
    } else {
      //TODO 此时微信版本太低（一般而言版本都是支持的）
      wx.showModal({
        title: '溫馨提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

  //用户数据解密
  decryptUserInfo: function (res, cb) {
    var that = this;
    //发起网络请求，用户数据验证、解密
    var openid = wx.getStorageSync('openid');
    wx.showLoading({
      title: '用户数据获取中...',
    })
    console.log(res)
    request.requestLoading(
        "/api/login/getUserMessage", {
          encryptedData: res.encryptedData,
          iv: res.iv,
          openid: openid,
        },
        'POST',
        true,
    ).then((res) => {
      wx.hideLoading()
      if (res.code == 1) {
        wx.setStorageSync('thirdInfo', res.data)
        typeof cb == "function" && cb();
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'text',
        });
      }
    }).catch((err) => {
      wx.hideLoading()
    });

  },
  init_config: function () {
    // console.log('init_config');
    return new Promise((resolve, reject) => {
      if (this.globalData.configData) {
        resolve(this.globalData.configData);
      } else {
        request.requestLoading(
            "/api/common/init_config",
            {},
            'GET',
        ).then((res) => {
          // console.log(res);
          this.globalData.configData = res.data;
          resolve(res.data);
        }).catch((err) => {
          // console.error(err);
          reject(err);
        });
      }
    })
  },
  decryptPhoneNumber: function (res, cb) {
    var that = this;
    //发起网络请求，用户数据验证、解密
    var openid = wx.getStorageSync('openid');
    wx.showLoading({
      title: '手机号获取中...',
    })
    var hideLoading=true;
    request.requestLoading(
        "/api/login/getPhone",
        {
          encryptedData: res.encryptedData,
          iv: res.iv,
          openid: openid,
        },
        'POST',
        true,
    ).then((res) => {
      hideLoading=false;
      wx.hideLoading()
      console.log(res);
      if (res.code == 1) {
        // 保存token
        wx.setStorageSync('token', res.data.userinfo.token);
        wx.setStorageSync('userInfo', res.data.userinfo)
        wx.setStorageSync('mobile', res.data.userinfo.mobile);
        that.globalData.userInfo = res.data.userinfo;
        typeof cb == "function" && cb(that.globalData.userInfo);
      } else {
        console.log(res);
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration:2000
        });
        //cb && cb(res.data);

      }
    }).catch((err) => {
      if(hideLoading){
        wx.hideLoading({
          success: (res) => {},
        })
      }
    });
  },
  getSystemInfo: function() {
    let that = this;
    wx.getSystemInfo({
      success: function(res) {
        let models = res.model;
        if (models.search('iPhone 6/7/8') != -1) {
          that.globalData.isIPhone6 = true
        }
      }
    });
  },
  //获取用户位置
  getLocation: function (cb) {
    var that = this;
    //授权判断
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userLocation'] == false) {
          // 拒绝授权，弹窗提示
          wx.showToast({
            title: '需要您的位置信息授权，才能查看附近的医院或商品',
            icon:'none'
          })

        } else {
          //调用位置接口
          wx.getLocation({
            type: 'gcj02', //默认为 wgs84 返回 gps 坐标，gcj02 返回可用于wx.openLocation的坐标
            success: function (res) {
              that.globalData.latitude = res.latitude;
              that.globalData.longitude = res.longitude;
              typeof cb == "function" && cb(res)
            },fail:function (res) {
              console.log(res);
              wx.showToast({
                title: '需要您的位置信息授权，才能查看附近的医院或商品',
                icon:'none'
              })
            }
          })
        }
      }
    })
  },
})